package com.quasar.hpatient.view.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.Toolbar;
import android.text.style.ForegroundColorSpan;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseFragment;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.httpmodel.DataHeadResult;
import com.quasar.hpatient.model.litePalmodel.Recorddb;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.model.operationmodel.AccountInfo;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.utils.Spanny;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.friends.FriendsListActivity_;
import com.quasar.hpatient.view.message.MyMessageActivity_;
import com.quasar.hpatient.view.personal.EditUserActivity_;
import com.quasar.hpatient.view.personal.HealthyArchivesActivity_;
import com.quasar.hpatient.view.personal.collection.CollectionActivity_;
import com.quasar.hpatient.view.personal.register.RegisterEditActivity_;
import com.quasar.hpatient.view.personal.setup.AboutActivity_;
import com.quasar.hpatient.view.personal.setup.MotionActivity_;
import com.quasar.hpatient.view.personal.setup.SettingActivity_;
import com.quasar.hpatient.view.prescription.AddPrescriptionActivity_;
import com.quasar.hpatient.view.prescription.AtPrescriptionActivity_;
import com.quasar.hpatient.view.socialContact.MyDynamicActivity_;
import com.quasar.hpatient.widget.ChoiceDoctorxDialog;
import com.quasar.hpatient.widget.MyQrodeDialog;
import com.quasar.hpatient.widget.MyView;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import chatui.Constant;
import chatui.DemoHelper;
import chatui.cacha.UserCacheManager;
import chatui.ui.GroupsActivity;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * author : 许建宏
 * Date: 2017/9/29 0029
 * View:个人中心
 */

@EFragment(R.layout.fragment_my)
public class MyFragment extends BaseFragment {

    String userCode=MainAppliaction.getInstance().getUserCode();
    Map<String, String> map = MainAppliaction.getInstance().MsgList();
    PatientInfoData patient= MainAppliaction.getInstance().getPatient();

    //昵称
    @ViewById(R.id.name)
    TextView name;
    //名字
    @ViewById(R.id.username)
    TextView username;
    //头像
    @ViewById(R.id.headimg)
    RoundedImageView headimg;
    //消息
    @ViewById(R.id.mv_news)
    MyView mv_news;
    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    @ViewById(R.id.operationDate)
    TextView operationDate;

    @AfterViews
    void init(){
        ViseLog.d("enter");
        initView();
        initData();
    }
    private int color(int value) {
        return MainAppliaction.getInstance().getResources().getColor(value);
    }

    @Override
    public void initView() {
        ViseLog.d("enter");
        main_toolbar.setTitle("个人中心");
    }



    public void initViewData(PatientInfoData patientInfo){
        Spanny spanny=new Spanny();
        spanny.append("姓名：", new ForegroundColorSpan(color(R.color.btcolor)));
        if (patientInfo.getRealName() == null || patientInfo.getRealName().length() == 0) {
            spanny.append("<--未设置-->",new ForegroundColorSpan(color(R.color.textcolor)));
        } else {
            spanny.append(patientInfo.getRealName(),new ForegroundColorSpan(color(R.color.textcolor)));
        }
        name.setText(spanny);

        Spanny spannyUser=new Spanny();
        spannyUser.append("手机号码：", new ForegroundColorSpan(color(R.color.btcolor)));
        //账号
        if (patientInfo.getPhone() != null && patientInfo.getPhone().length()>0) {
            spannyUser.append(patientInfo.getPhone(),new ForegroundColorSpan(color(R.color.textcolor)));
        }else{
            spannyUser.append("<--未设置-->",new ForegroundColorSpan(color(R.color.textcolor)));
        }
        username.setText(spannyUser);

        //头像
        if(patientInfo.getCover()!=null && patientInfo.getCover().length()>0){
            Glide.with(this).load(RetrofitConnection.PHOTOURL+patientInfo.getCover()).into(headimg);
        }else{
            Glide.with(this).load(R.mipmap.nopic).into(headimg);
        }
        Spanny spannyTime=new Spanny();
        spannyTime.append("手术时间：", new ForegroundColorSpan(color(R.color.btcolor)));
        if(patientInfo.getPatientOperationInfo()!=null){
            ViseLog.d("进入手术时间"+patientInfo.getPatientOperationInfo().getOperationTime());
            if(patientInfo.getPatientOperationInfo().getOperationTime()!=null && patientInfo.getPatientOperationInfo().getOperationTime().length()>0){
                if(TimeZoneUtil.remainDateToString(patientInfo.getPatientOperationInfo().getOperationTime()).length()==0
                        || TimeZoneUtil.remainDateToString(patientInfo.getPatientOperationInfo().getOperationTime())==null){
                    spannyTime.append("0天",new ForegroundColorSpan(color(R.color.textcolor)));
                    ViseLog.d("计算手术时间++++++"+TimeZoneUtil.remainDateToString(patientInfo.getPatientOperationInfo().getOperationTime()));
                }else{
                    spannyTime.append(TimeZoneUtil.remainDateToString(patientInfo.getPatientOperationInfo().getOperationTime()),new ForegroundColorSpan(color(R.color.textcolor)));
                }
                operationDate.setText(spannyTime);
            }
        }

    }

    @Override
    public void initData() {

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    //个人信息
    @Click(R.id.ll_detailed)
    public void ll_detailed(){
        EditUserActivity_.intent(this).start();
    }

    //设置
    @Click(R.id.mv_setup)
    public void mv_setup(){
        SettingActivity_.intent(getActivity()).start();
    }

    //关于我们
    @Click(R.id.mv_about)
    public void mv_about(){
        AboutActivity_.intent(this).start();
    }

    //我的收藏
    @Click(R.id.mv_collection)
    public void mv_collection(){
        CollectionActivity_.intent(this).start();
    }
    //我的好友
    @Click(R.id.mv_friends)
    public void mv_friends(){
        FriendsListActivity_.intent(getActivity()).start();
    }
    //我的消息
    @Click(R.id.mv_news)
    public void mv_news(){
        MyMessageActivity_.intent(this).start();
    }
    //我的发帖
    @ViewById(R.id.mv_post)
    MyView mv_post;
    @Click(R.id.mv_post)
    public void mv_post(){
        MyDynamicActivity_.intent(this).start();
    }
    //健康档案
    @Click(R.id.mv_archives)
    public void mv_archives(){
        HealthyArchivesActivity_.intent(this).start();
    }
    //我的药单
    @Click(R.id.mv_prescription)
    public void mv_prescription(){
        //当前药单
        AtPrescriptionActivity_.intent(getActivity()).start();
    }

    //计步器
    @Click(R.id.mv_step)
    public void mv_step(){
        MotionActivity_.intent(getActivity()).start();
    }
    //我的二维码
    @Click(R.id.iv_qrode)
    public void iv_qrode(){
        MyQrodeDialog dialog = new MyQrodeDialog(getActivity());
        dialog.show();
    }

    //修改用户信息成功后重新获取个人信息
    public void PostUserinfo(){

        String userName=null;
        if(patient.getPhone()!=null && patient.getPhone().length()>0){
            userName=patient.getPhone();
        }else{
            userName=patient.getName();
        }

        RetrofitConnection.getRoutineApi()
                .UserInformation(userCode,userName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<DataHeadResult<PatientInfoData>>() {
                    @Override
                    public void accept(DataHeadResult<PatientInfoData> patientInfoDataDataHeadResult) throws Exception {
                        if(!patientInfoDataDataHeadResult.getMsgCode().equals("0x00000000")){
                            throw new RuntimeException(map.get(patientInfoDataDataHeadResult.getMsgCode()));
                        }
                    }
                })
                .subscribe(new Observer<DataHeadResult<PatientInfoData>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull DataHeadResult<PatientInfoData> patientInfoDataDataHeadResult) {
                        ViseLog.d("onNext"+patientInfoDataDataHeadResult.getData());
                        AccountInfo.saveAccount(getActivity(), patientInfoDataDataHeadResult.getData());
                        initViewData(patientInfoDataDataHeadResult.getData());

                        UserCacheManager.save(patientInfoDataDataHeadResult.getData().getBmobUserName(),
                                patientInfoDataDataHeadResult.getData().getRealName() ,
                                RetrofitConnection.PHOTOURL+patientInfoDataDataHeadResult.getData().getCover());

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        ViseLog.d("onError"+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        ViseLog.d("onComplete");
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateEvent closeEvent){
        if(closeEvent.type.equals(ConstantManger.eventUserInfo)){
            PostUserinfo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        PatientInfoData patient= MainAppliaction.getInstance().getPatient();
        initViewData(patient);

        DemoHelper sdkHelper = DemoHelper.getInstance();
        sdkHelper.pushActivity(getActivity());

        refreshUIWithMessage();

        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        registerBroadcastReceiver();

    }

    /**
     * 获取环信未读消息数量
     * 消息数量
     * update unread message count0
     */

    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver broadcastReceiver;

    private void registerBroadcastReceiver() {
        broadcastManager = LocalBroadcastManager.getInstance(getActivity());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
        intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
        // intentFilter.addAction(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION);*/
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                updateUnreadLabel();
                //刷新fragment
                String action = intent.getAction();
                if (action.equals(Constant.ACTION_GROUP_CHANAGED)) {
                    if (EaseCommonUtils.getTopActivity(getActivity()).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            }
        };
        broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }


    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
            for (EMMessage message : messages) {
                DemoHelper.getInstance().getNotifier().onNewMsg(message);
            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //red packet code : 处理红包回执透传消息
            for (EMMessage message : messages) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                final String action = cmdMsgBody.action();//获取自定义action
               /* if (action.equals(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                    RedPacketUtil.receiveRedPacketAckMessage(message);
                }*/
            }
            //end of red packet code
            refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };


    private void refreshUIWithMessage() {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
            }
        });
    }

    public void updateUnreadLabel() {
        Integer count = getUnreadMsgCountTotal();
        if(count!=null){
            mv_news.setNum(count);
        }
    }

    /**
     * get unread message count
     *
     * @return
     */

    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMessageCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }
}
